package com.topscomm.mpm.script;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.ICboApprovalNodeInsService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.cbo.service.impl.CboApprovalNodeInsService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.mpm.MpmScript;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.service.*;
import com.topscomm.mpm.service.impl.*;
import com.topscomm.mpm.utils.ConvertTimeUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wudaliang
 * @date 2021/1/11
 * @description:
 * @modify:
 */
public class MpmProjectPlanScript extends MpmScript {



    /**
     * @author: wudaliang
     * @date: 2021-01-19
     * @description:
     * @return: void
     * @modify:
     */
    @Transactional
    public void projectPlanAfterApproval(ITapService service, TapEntity entity)throws Exception{
        //审批节点实例
        CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
        String sourceid = ConvertUtil.convertToString(nodeins.getSourceid());
        IMpmProjectTaskService mpmProjectTaskService = (MpmProjectTaskService) SpringUtil.getBean("mpmProjectTaskService");
        IMpmProjectPlanService mpmProjectPlanService = (MpmProjectPlanService) SpringUtil.getBean("mpmProjectPlanService");
        IMpmProjectMilepostService mpmProjectMilepostService = (MpmProjectMilepostService) SpringUtil.getBean("mpmProjectMilepostService");
        IMpmProjectService mpmProjectService = (MpmProjectService) SpringUtil.getBean("mpmProjectService");
        StringBufferProxy sql = new StringBufferProxy();
        // 查询新策划书
        MpmProjectPlanEntity mpmNewPlan = mpmProjectPlanService.queryById(sourceid);
        //查询是否有生效的策划书
        sql.appendLineSingle("state=9 and enabled=1 and projectcode= '{0}'",mpmNewPlan.getProjectcode());
        List<MpmProjectPlanEntity> mpmProjectPlanEntities = mpmProjectPlanService
            .queryByWhere(sql.toString());
        if(mpmProjectPlanEntities.size()>0) {
            // 查询旧策划书
            MpmProjectPlanEntity mpmOldPlan = mpmProjectPlanEntities.get(0);
            // 查询旧策划书的里程碑及任务
            sql.clear();
            sql.appendLineSingle("planid = '{0}'",mpmOldPlan.getId());
            List<MpmProjectMilepostEntity> mpmOldMilepostList = mpmProjectMilepostService
                    .queryByWhere(sql.toString());
            // 查询新策划书的里程碑及任务
            sql.clear();
            sql.appendLineSingle("planid = '{0}'",mpmNewPlan.getId());
            List<MpmProjectMilepostEntity> mpmNewMilepostList = mpmProjectMilepostService
                    .queryByWhere(sql.toString());
            // 将旧策划书有效性置为0，并把旧策划书下的里程碑及任务有效性全部置为0,
            // 将新策划书有效性置为1，并把新策划书下里程碑及任务有效性全部置为1，同步新里程碑及任务和旧里程碑及任务的状态
            mpmProjectPlanService.disableOldPlanAndMilePost(mpmOldPlan,mpmOldMilepostList,mpmNewPlan,mpmNewMilepostList);
            // 修改任务中的里程碑及任务名称
            mpmProjectPlanService.updateTaskMilepostName(mpmNewPlan,mpmNewMilepostList);
            // 如果新里程碑及任务改变了里程碑及任务责任人，需要将任务反馈和任务关闭的里程碑及任务责任人节点的办理人进行修改
            mpmProjectPlanService.updateResponsibleCode(mpmOldMilepostList,mpmNewMilepostList);
        } else {
            sql.clear();
            sql.appendSingle("planid = '{0}'",mpmNewPlan.getId());
            // 获取该策划书下的里程碑及任务
            List<MpmProjectMilepostEntity> mpmProjectMilepostEntityList = mpmProjectMilepostService
                .queryByWhere(sql.toString());
            List<BasicEntity> updateMilepostEntity = new ArrayList<>();
            // 将各个里程碑及任务的状态置为1,并更新任务的里程碑及任务名称字段
            for (MpmProjectMilepostEntity mpmProjectMilepostEntity:mpmProjectMilepostEntityList) {
                mpmProjectMilepostEntity.setEnabled(1);
                updateMilepostEntity.add(mpmProjectMilepostEntity);
                mpmProjectPlanService.updateMilepostNameForTask(mpmProjectMilepostEntity);
            }
            mpmProjectMilepostService.updateBatch(updateMilepostEntity);
        }

        //查询项目entity
        sql.clear();
        sql.appendLineSingle("projectcode = '{0}'", mpmNewPlan.getProjectcode());
        MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(sql.toString());
        // 首次策划更新项目状态，策划时间等主表数据，二次策划需要判断里程碑是否全部完成
        if(!ObjectUtil.isEmpty(mpmProjectEntity) && CollectionUtil.isEmpty(mpmProjectPlanEntities)){
            //策划审批结束，更细项目状态。更新状态：执行阶段（策划审批结束到复盘审批结束）
            mpmProjectEntity.setSchedulestate(7);
            mpmProjectEntity.setDesignenddate(new Date());
            if (MpmSystemConst.ProjectLevel.A.equals(mpmProjectEntity.getProjectlevel())) {
                // 获取7天之后的日期(第一次策划审批结束后一周)
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DATE, 7);
                ConvertTimeUtil.convertToThisWeekMonday(calendar);
                mpmProjectEntity.setMeetbegindate(calendar.getTime());
            }
            mpmProjectService.updateEntity(mpmProjectEntity);
        } else if (!ObjectUtil.isEmpty(mpmProjectEntity) && !CollectionUtil.isEmpty(mpmProjectPlanEntities)) {
            mpmProjectTaskService.queryMilepostAllFinished(mpmProjectEntity);
        }
    }

    /**
     * @author
     * @date
     * @description: 策划审批结束，给项目经理、项目组成员发送消息，批量下发任务并给任务、里程碑及任务责任人发送消息提醒。
     *              把所有消息提醒整合在一个结束脚本中，防止其中一个脚本报错时把部分消息发送出去。
     * @modify:
     */
    @Transactional
    public void projectPlanSendMessage(ITapService service, TapEntity entity) throws Exception {
        // 审批点实例
        CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
        String sourceid = ConvertUtil.convertToString(nodeins.getSourceid());
        String sourcetype = ConvertUtil.convertToString(nodeins.getSourcetype());
        MpmProjectPlanService mpmProjectPlanService = (MpmProjectPlanService) SpringUtil.getBean("mpmProjectPlanService");
        MpmProjectTeamService mpmProjectTeamService = (MpmProjectTeamService) SpringUtil.getBean("mpmProjectTeamService");
        MpmProjectMilepostService mpmProjectMilepostService = (MpmProjectMilepostService) SpringUtil.getBean("mpmProjectMilepostService");
        MpmProjectTaskService mpmProjectTaskService = (MpmProjectTaskService) SpringUtil.getBean("mpmProjectTaskService");
        MpmProjectService mpmProjectService = (MpmProjectService) SpringUtil.getBean("mpmProjectService");
        MpmProjectAppointmentService mpmProjectAppointmentService = (MpmProjectAppointmentService) SpringUtil.getBean("mpmProjectAppointmentService");
        // 查询策划书
        MpmProjectPlanEntity mpmProjectPlanEntity = mpmProjectPlanService.queryById(sourceid);
        // 查询项目id
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectcode = '{0}'", mpmProjectPlanEntity.getProjectcode());
        List<MpmProjectEntity> mpmProjectEntity = mpmProjectService.queryByWhere(sql.toString());
        if (CollectionUtil.isEmpty(mpmProjectEntity)) {
            return;
        }
        long mpmId = mpmProjectEntity.get(0).getId();
        // 查询项目是否为第一次策划
        int count = mpmProjectPlanService.getCount(sql.toString());
        if (count > 1) {
            // 若不是第一次策划则给项目经理非省总、省区PMO、变更涉及人员发送消息提醒
            String contentInfo = "策划";
            mpmProjectPlanService.sendMessagePlanToPMO(mpmProjectPlanEntity, mpmProjectEntity.get(0));
            mpmProjectTeamService.sendMessageToPM(sourceid, sourcetype, contentInfo, mpmProjectEntity.get(0));
        } else {
            // 策划审批通过消息提醒，通知项目经理
            mpmProjectPlanService.sendMessageAppAndSys(mpmProjectPlanEntity, ConvertUtil.convertToString(mpmId));
        }
        // 批量下发任务并通知任务责任人任务已下发
        mpmProjectTaskService.sendMessageToTaskResponsible(mpmProjectPlanEntity.getProjectcode(), count);
    }
}
